import * as React from 'react'
import { message, Upload, Button } from 'antd'
import { serverIP } from '../../service/api'
import Cache from '../../utils/cache'
export interface State {
  loading: boolean
  files: any []
  isSuc: boolean
}

export interface Props {
  url: string
  showFile?: boolean
  fileType: string
  disabled?: boolean
  title?: string
  onChange : (param: any) => void
}

export default class HideUpload extends React.Component<Props, State> {
  state={
    loading: false,
    files: [],
    isSuc: false
  }
  getFiles = () => {
    return this.state.files
  }
  setFiles=(guid: string, url: string)=>{
    if(url!=null && url!='')
      this.setState({ isSuc: true, files: [{ guid,url }]})
  }
  clearFiles = () => {
    this.setState({ files: [] })
  }
  beforeUpload = (file: any) => {
    const { fileType } = this.props
    let isJPG=true
    if(fileType)
        isJPG=fileType.indexOf(file.type)>=0
    if (!isJPG) {
      message.error("请上传"+fileType+"类型文件")
    }
    const isLt2M=true
    return isJPG && isLt2M
  }
  handleChange = (info: any) => {
    const { file: { status, response }, fileList } = info
    if (status === 'uploading') {
      this.setState({ loading: true })
      return
    }
    if (status === 'done') {
      message.success(`上传成功`)
      this.setState({ loading: false, isSuc: true, files: fileList })
      if(this.props.onChange){
        this.props.onChange(response)
      }
    }
    if (status === 'error') {
      message.error(`${info.file.name} 上传失败`)
      this.setState({ loading: false })
    }
  }
  render() {
    const { url, disabled, title, showFile } = this.props
    const { loading, files, isSuc } = this.state
    let file: any = files [0]
    return(
      <span>
        <Upload  
          name='file'  
          action= {serverIP+url} headers={{ 'token': Cache.sessionGet('LOGIN_USER').token }} 
          showUploadList={false}
          beforeUpload={this.beforeUpload}
          onChange={this.handleChange}
          disabled={loading}>
          <Button loading={loading} icon="upload" disabled={ disabled || false}> { title || "上传附件"}</Button>
        </Upload>
        {(isSuc && showFile)? <span>
          <a href={file.url} target="_blank"> <span>查看</span> </a>
        </span>:""}
      </span>
    )
  }
}